package cn.maihe.elg.operation.security.auth.ajax;

import cn.maihe.elg.operation.config.ZtAccountInfo;
import cn.maihe.elg.operation.model.enums.UserType;
import cn.maihe.elg.operation.security.model.UserContext;
import cn.maihe.elg.operation.security.model.token.JwtToken;
import cn.maihe.elg.operation.security.model.token.JwtTokenFactory;
import cn.maihe.elg.operation.utils.DateUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author JHWei
 * 2018/7/9 下午7:48
 */
@Component
public class AjaxAwareAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    private final ObjectMapper mapper;
    private final JwtTokenFactory tokenFactory;

    @Resource
    private ZtAccountInfo ztAccountInfo;

    @Autowired
    public AjaxAwareAuthenticationSuccessHandler(final ObjectMapper mapper, final JwtTokenFactory tokenFactory) {
        this.mapper = mapper;
        this.tokenFactory = tokenFactory;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        UserContext userContext = (UserContext) authentication.getPrincipal();

        JwtToken accessToken = tokenFactory.createAccessJwtToken(userContext);
        JwtToken refreshToken = tokenFactory.createRefreshToken(userContext);
        response.setContentType("application/json;charset=UTF-8");
        Map<String, String> tokenMap = new HashMap<String, String>(16);
        tokenMap.put("token", accessToken.getToken());
        tokenMap.put("refreshToken", refreshToken.getToken());
        if(userContext.getOrgId()!=null){
            tokenMap.put("orgId",userContext.getOrgId().toString());
        }else{
            tokenMap.put("orgId","-1");
        }
        tokenMap.put("ztOpenBankName",ztAccountInfo.getOpenBankName());

        String ztAccNo = ztAccountInfo.getAccNo();
        // 兼容子账号场景
        String subAccount = userContext.getSubAccount();
        if(StringUtils.isNotBlank(subAccount)){
            ztAccNo += subAccount;
        }
        tokenMap.put("ztAccNo",ztAccNo);
        tokenMap.put("ztAccName",ztAccountInfo.getAccName());

        tokenMap.put("orgCode",userContext.getOrgCode());
        tokenMap.put("orgName",userContext.getOrgName());
        tokenMap.put("name",userContext.getName());
        tokenMap.put("userType",userContext.getUserType().toString());
        tokenMap.put("loginCount", (userContext.getUser().getLoginCount()+1)+"");
        if(userContext.getUser().getPwdExpiredTime().before(new Date())){
//            tokenMap.put("pwdExpire","1");
        }
        Date date = userContext.getUser().getLastLoginTime();
        if(date!=null){
            tokenMap.put("lastLoginTime", DateUtil.formateDate(date,DateUtil.FORMAT_DATETIME));
        }else{
            tokenMap.put("lastLoginTime", "");
        }

        if(UserType.BIDDER.getType() ==  userContext.getUserType()){
            tokenMap.put("bidderId",String.valueOf(userContext.getBidderId()));
            tokenMap.put("bidderStatus",String.valueOf(userContext.getBidderStatus()));
        }


        response.setStatus(HttpStatus.OK.value());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        mapper.writeValue(response.getWriter(), tokenMap);

        clearAuthenticationAttributes(request);
    }

    /**
     * Removes temporary authentication-related data which may have been stored
     * in the session during the authentication process..
     *
     */
    protected final void clearAuthenticationAttributes(HttpServletRequest request) {
        HttpSession session = request.getSession(false);

        if (session == null) {
            return;
        }

        session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
    }
}
